package com.gxitsky.channel;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gxing
 * @desc 渠道管理器
 * @date 2022/1/22
 */
@Configuration
public class ChannelManager {

    public static ConcurrentHashMap<String, ChannelConfig> channelConfigMap = new ConcurrentHashMap<>();

    @Autowired
    private ResourcePatternResolver patternResolver;

    @PostConstruct
    public void init() {
        try {
            Resource[] resources = patternResolver.getResources("classpath:config/*.yml");
            Yaml yaml = new Yaml();
            for (Resource resource : resources) {
                InputStream inputStream = resource.getInputStream();
                ChannelConfigLoader channelConfigLoader = yaml.loadAs(inputStream, ChannelConfigLoader.class);
                ChannelConfig channelConfig = channelConfigLoader.getChannelConfig();
                channelConfig.init();
                channelConfig.setChannelCode(FilenameUtils.getBaseName(resource.getFilename()));
                channelConfigMap.put(channelConfig.getChannelCode().toLowerCase(), channelConfig);
                //            channelConf.getTradeConfs().forEach(td -> tradeConfMap.put(channelConf.getChannelCode().toLowerCase() + td.getTrade().toLowerCase() ,td));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
